﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using Fcdbas.Core.Net;
using FileTransferProtocol;
namespace FileTransferSrv
{
   
    public partial class MainForm : Form
    {
        private string configPath;
        public static string LogPath;
        private SocketServer FFServer;
        public OnEventMessageDelegate FEvent;
        private int FConnectionCount;
        public MainForm()
        {
            InitializeComponent();
            LogPath = AppDomain.CurrentDomain.BaseDirectory + "Log";
        }
        public void Event(string eventMessage)
        {
            Event(eventMessage, false);
        }

        public void Event(string eventMessage, bool ex)
        {

            if (lstMessages.InvokeRequired)
            {
                lstMessages.Invoke(new OnEventMessageDelegate(delegate(string s) { Event(s); }), eventMessage);
            }
            else
            {

                if (eventMessage.Contains("Connected"))
                {
                    Interlocked.Increment(ref FConnectionCount);
                }

                if (eventMessage.Contains("Disconnected"))
                {
                    Interlocked.Decrement(ref FConnectionCount);
                }

                this.Text = FConnectionCount.ToString() + " Connections";

                string[] s = eventMessage.Split('\n');

                for (int i = s.Length - 1; i >= 0; i--)
                {
                    lstMessages.BeginUpdate();
                    lstMessages.Items.Insert(0, s[i]);

                    if (lstMessages.Items.Count > 100)
                        lstMessages.Items.RemoveAt(100);

                    lstMessages.EndUpdate();
                }

            }

        }
        private ConfigSrv config;
        private void MainForm_Load(object sender, EventArgs e)
        {
            configPath = AppDomain.CurrentDomain.BaseDirectory + "ConfigSrv.xml";
            config = Fcdbas.Core.Xml.XmlHelper.ToXmlFileEntity<ConfigSrv>(configPath);
            if (config == null)
                config = new ConfigSrv();
            else
            {
                this.txtDownLoadPath.Text = config.DownLoadPath;
                this.txtPath.Text = config.SavePath;
                this.txtPort.Text = config.Port.ToString();
            }
            FEvent = new OnEventMessageDelegate(Event);
            FConnectionCount = 0;
            FFServer = null;
            
        }
        public void OnException(Exception ex)
        {
            Event("Service Exception! - " + ex.Message, true);
            Event("------------------------------------------------", true);
        }
        private FileTransferServer fileTfSrv;
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtPath.Text) || string.IsNullOrEmpty(txtPort.Text))
            {
                MessageBox.Show("保存路径或者端口号不能为空！");
                return;
            }
            if (FFServer == null)
            {
                fileTfSrv = new FileTransferServer(FEvent, txtPath.Text,txtDownLoadPath.Text);
                FFServer = new SocketServer(CallbackThreadType.ctIOThread,fileTfSrv , DelimiterType.dtMessageTailExcludeOnReceive, Encoding.GetEncoding(1252).GetBytes("%$#@^&"), 1024 * 10, 1024 * 160);
            }
            AddListener();
            FFServer.Start();
            btnStop.Enabled = true;
            btnStart.Enabled = false;
        }
        private void AddListener()
        {

            FFServer.AddListener(String.Empty, new IPEndPoint(IPAddress.Any, int.Parse(txtPort.Text)), EncryptType.etNone, CompressionType.ctNone,null, 50, 3);
            
        }
        private void btnBrows_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtPath.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Fcdbas.Core.Xml.XmlHelper.ToXmlFile(config, configPath);
            if(FFServer != null && FFServer.Active)
                FFServer.Stop();
            if(fileTfSrv != null)
                fileTfSrv.SaveTranferFile();
        }

        private void btnDownLoad_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtDownLoadPath.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            FFServer.Stop();
            this.btnStart.Enabled = true;
            this.btnStop.Enabled = false;
        }

        private void txtPath_TextChanged(object sender, EventArgs e)
        {
            this.config.SavePath = txtPath.Text;
        }

        private void txtDownLoadPath_TextChanged(object sender, EventArgs e)
        {
            this.config.DownLoadPath = txtDownLoadPath.Text;
        }

        private void txtPort_TextChanged(object sender, EventArgs e)
        {
            this.config.Port = int.Parse(txtPort.Text);
        }
    }
}
